// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// const rp = require('request-promise')
const axios = require('axios')

const db = cloud.database()

const URL = 'https://apis.imooc.com/personalized?icode=2F365711BC4CFD31'

//数据库playlist集合
const playlistCollection = db.collection('playlist')

// 云函数入口函数
exports.main = async (event, context) => {
const {data} = await axios.get(URL)
if(data.code >= 1000){
  console.log(data.msg);
  return 0
}

const playlist = data.result
// const list = await playlistCollection.get()

//小程序端在获取集合数据时服务器一次默认并且最多返回 20 条记录，云函数端这个数字则是 100
//突破获取数据条数的限制
// 先取出集合记录总数
const countResult = await playlistCollection.count()
const MAX_LIMIT = 100
//获取 countResult 中的总条数
const total = countResult.total
// 计算需分几次取
const batchTimes = Math.ceil(total / MAX_LIMIT)
// 承载所有读操作的 promise 的数组
const tasks = []
for (let i = 0; i < batchTimes; i++) {
  //skip:从第几条数据开始读取   limit:每次读取的条数
  const promise = playlistCollection.skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
  tasks.push(promise)
}
let list = {
  data:[]
}
if(tasks.length > 0){
  list = (await Promise.all(tasks)).reduce((acc, cur) => {
    return {
      data: acc.data.concat(cur.data),
    }
  })
}
console.log(playlist);

// 对请求的数据进行去重
const newData= []
//用两层for循环,将请求来的数据,进行去重
for(let i = 0;i < playlist.length;i++){
  let flag = true
  for(let j = 0;j < list.data.length;j++){
    if(playlist[i].id === list.data[j].id){
      flag = false
      break
    }
  }
  if(flag){
    // 更新代码: 给每个歌单信息增加createTime属性
    let pl = playlist[i]
    pl.createTime = db.serverDate()
    // newData.push(playlist[i])
    newData.push(pl)
  }
}

  // 循环 遍历 .将数据插入到数据库中
  if(newData.length > 0){
    await playlistCollection.add({
      data:[...newData]
    }).then(res => {
      console.log("插入成功!");
    }).catch(err =>{
      console.log("插入失败!");
    })
  }
 
}